package com.fg.cloud.agency.controller.order;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.fg.cloud.agency.controller.BaseAgencyController;
import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.Result;
import com.fg.cloud.common.ServiceException;
import com.fg.cloud.common.StatusCode;
import com.fg.cloud.common.finals.Agency;
import com.fg.cloud.common.finals.OrderStatus;
import com.fg.cloud.common.finals.UserType;
import com.fg.cloud.common.quantity.ResultType;
import com.fg.cloud.common.reflection.ParamsReflect;
import com.fg.cloud.manager.entry.BaseEntity;
import com.fg.cloud.manager.entry.agency.vo.AgencyUserVo;
import com.fg.cloud.manager.entry.factory.FactoryProcessEntity;
import com.fg.cloud.manager.entry.factory.vo.FactoryProcessVo;
import com.fg.cloud.manager.entry.order.OrderCheckEntity;
import com.fg.cloud.manager.entry.order.OrderDetailEntity;
import com.fg.cloud.manager.entry.order.OrderInfoEntity;
import com.fg.cloud.manager.entry.order.vo.OrderDetailVo;
import com.fg.cloud.manager.entry.order.vo.OrderInfoVo;
import com.fg.cloud.manager.mapper.factory.FactoryProcessMapper;
import com.fg.cloud.manager.service.order.OrderCheckService;
import com.fg.cloud.manager.service.order.OrderDetailService;
import com.fg.cloud.manager.service.order.OrderInfoService;

/**
 * Description:经销商订单模块
 * @author around
 * @date 2017年9月6日下午10:05:48
 */
@Controller
@RequestMapping(value = "/agencyOrder")
public class AgencyOrderController extends BaseAgencyController {

	@Autowired
	private OrderInfoService agency_orderService;
	@Autowired
	private OrderDetailService detailService ;
	@Autowired
	private OrderCheckService checkService ;
	@Autowired
	private FactoryProcessMapper processMapper ;
	
	/**
	 * Description:经销商端查询基础订单头信息
	 * @param entity
	 * @author around
	 * @date 2017年9月6日下午10:36:11
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping("findOrderInfo")
	@ResponseBody
	public void findOrderInfo(HttpServletResponse response, Integer page, Integer rows, 
			String sort, String order, OrderInfoEntity entity, String filterText) {
		try {
			AgencyUserVo user = getCurrentAgencyUser();
			PageUtils<OrderInfoEntity> pageinfo = 
					new PageUtils<OrderInfoEntity>(page, rows, sort, order);
			Map<String, Object> condition = pageinfo.getCondition();
			condition.put("ageId", user.getAgeId());
			condition.put("facId", user.getFacId());
			condition.put("filterText", filterText);
			//condition.put("ageName", entity.getAgeName());
			condition.put("orderStatus", OrderStatus.PENDINGSHIP);
			
			agency_orderService.findList(pageinfo);
			doResult(response, true, StatusCode.FINDSUCCESS, pageinfo, ResultType.FIND_SUCCESS);
		} catch (Exception e) {
			e.printStackTrace();
			doResult(response, false, StatusCode.EXCEPTIONERROR, null, ResultType.FIND_FAULT);
		}
	}
	
	/**
	 * Description:新增订单
	 * @param req
	 * @param resp
	 * @param order
	 * @author liushengchao
	 * @date  2017年9月11日上午10:52:53
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value="addorder")
	@ResponseBody
	public void addOrder(HttpServletRequest req ,HttpServletResponse resp, String data){
		try {
			OrderInfoVo entity = JSON.parseObject(
					StringEscapeUtils.unescapeHtml4(data), OrderInfoVo.class);
			String type = "addOrder" ;
			Result result  = agency_orderService.AgencyInsertOrder(entity,type);
			doResult(resp, result.isSuccess(), result.getCode(), 
					result.getData(), result.getMessage());
		} catch (ServiceException e) {
			doResult(resp, false, e.getCode(), null, e.getMessage());
		} catch (Exception e) {
			doResult(resp, false, StatusCode.EXCEPTIONERROR, null, ResultType.ERROE);
			e.printStackTrace();
		}
	}
	
	/**
	 * Description:订单信息保存（不进入正式流程）
	 * @param req
	 * @param resp
	 * @param order  订单信息
	 * @author liushengchao
	 * @date  2017年9月11日下午3:08:43
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value="/saveorder")
	@ResponseBody
	public void saveOrder(HttpServletRequest req ,HttpServletResponse resp,String data){
		try {
			OrderInfoVo entity = JSON.parseObject(
					StringEscapeUtils.unescapeHtml4(data), OrderInfoVo.class);
			String type = "save" ;
			Result result  = agency_orderService.AgencyInsertOrder(entity,type);
			doResult(resp, result.isSuccess(), result.getCode(), 
					result.getData(), result.getMessage());
		} catch (ServiceException e) {
			doResult(resp, false, e.getCode(), null, e.getMessage());
		} catch (Exception e) {
			doResult(resp, false, StatusCode.EXCEPTIONERROR, null, ResultType.ERROE);
			e.printStackTrace();
		}
	}
	
	/**
	 * Description:订单修改
	 * @param req
	 * @param resp
	 * @param order
	 * @author liushengchao
	 * @date  2017年9月11日下午3:18:20
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value="modify")
	@ResponseBody
	public void modify(HttpServletRequest req ,HttpServletResponse resp,String data){
		try {
			OrderInfoEntity entity = JSON.parseObject(
					StringEscapeUtils.unescapeHtml4(data), OrderInfoEntity.class);
			if(null == entity || entity.getOrderStatus() < 9){
				doResult(resp, false, StatusCode.NOPERMISS, null, "订单已进入正式流程，不能修改");
				return ;
			}
			Result result = agency_orderService.AgencyModifyOrder(entity);
			doResult(resp, result.isSuccess(), result.getData(), result.getMessage());
			
		} catch (ServiceException e) {
			doResult(resp, false, e.getCode(), null, e.getMessage());
		} catch (Exception e) {
			doResult(resp, false, StatusCode.SAVEERROR, null, ResultType.ERROE);
			e.printStackTrace();
		}
	}
	
	/**
	 * Description:查询订单列表
	 * @param req
	 * @param resp
	 * @param search 搜索框查询条件
	 * @param searchCondition 高级查询条件
	 * @param page 当前页
	 * @param rows 每页条数
	 * @param sort 排序字段
	 * @param order 排序规则
	 * @author liushengchao
	 * @date  2017年9月11日下午3:36:45
	 */
	//@ExceptionHandler(UnauthorizedException.class)
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value="/findlist")
	@ResponseBody
	public void findList(HttpServletRequest req ,HttpServletResponse resp,String search,
			OrderInfoVo searchCondition,Integer page, Integer row, String sort, String order
			,String statusStr) {
		try {
			PageUtils<BaseEntity> pageinfo = new PageUtils<BaseEntity>(page, row, sort, order);
			Map<String,Object> condition = ParamsReflect.getParamsByReflect(searchCondition);
			pageinfo.setCondition(condition);
			pageinfo.setFacId(getCurrentAgencyUser().getFacId());
			pageinfo.setAgeId(getCurrentAgencyUser().getAgeId());
			
			agency_orderService.findList(pageinfo, search, null, null, statusStr,null);

			doResult(resp, true, StatusCode.FINDSUCCESS, pageinfo, "查询订单成功");
		} catch (Exception e) {
			doResult(resp, false, StatusCode.SAVEERROR, null, ResultType.ERROE);
			e.printStackTrace();
		}
	}
	
	/**
	 * Description:查询订单详情
	 * @param req
	 * @param resp
	 * @param id 订单ID
	 * @author liushengchao
	 * @date  2017年9月12日上午10:44:54
	 */
	@RequiresRoles(UserType.AGENCY)
	@RequestMapping(value="/detail")
	@ResponseBody
	public void orderDetail(HttpServletRequest req ,HttpServletResponse resp,Long id,
			String orders,String sort){
		AgencyUserVo user = getCurrentAgencyUser() ;
		Long facId = user.getFacId();
		if(id < 1){
			doResult(resp, false, StatusCode.LACKVALUE, null, "订单ID不能为空");
			return ;
		}
		OrderInfoEntity order = agency_orderService.find(id);
		if(order == null ){
			doResult(resp, false, StatusCode.NORETRUNDATA, null, "查询结果为空");
			return ;
		}
		List<OrderDetailEntity> detail = detailService.selectByOrderId(id,orders,sort);
		List<OrderCheckEntity> operatorRecord = checkService.selectByOrderId(id);
		if(detail == null || detail.size() < 0){
			doResult(resp, false, StatusCode.NORETRUNDATA, null, "该订单没有商品信息");
			return ;
		}
		List<FactoryProcessVo> processList = new ArrayList<FactoryProcessVo>();
		processList = getOrderProcess(order, facId);
		System.out.println(processList.toString());
		//String detailStr = JSON.toJSONString(detail);
		//order.setDetails(detailStr);
		order.setProcessList(processList);
		order.setListDetails(detail);
		order.setOperatorRecords(operatorRecord);
		doResult(resp, true, StatusCode.FINDSUCCESS, order, "查询成功");
	}
	
	/**
	 * Description:获取订单的整个流程信息
	 * @param order 订单信息
	 * @param facId 厂商信息
	 * @return List<FactoryProcessVo>
	 * @author liushengchao
	 * @date  2017年9月26日下午7:19:20
	 */
	public List<FactoryProcessVo> getOrderProcess(OrderInfoEntity order ,Long facId){
		FactoryProcessEntity processEntity = processMapper.selectByfacId(facId);
		List<FactoryProcessVo> processList = new ArrayList<>();
		int orderStatus = order.getOrderStatus();
		FactoryProcessVo process0 = new FactoryProcessVo();
		process0.setProcessName("开始");
		process0.setProcessStatus(true);
		processList.add(process0);
		FactoryProcessVo process1 = new FactoryProcessVo();
		process1.setProcessName("业务审核");
		process1.setProcessStatus(false);
		processList.add(process1);
		FactoryProcessVo process2 = new FactoryProcessVo();
		if(orderStatus == 10 ){
			if(orderStatus == 1){
				process1.setProcessName("业务审核");
				process1.setProcessStatus(true);
				processList.add(process1);
			}
			process2.setProcessName("订单作废");
			process2.setProcessStatus(true);
			processList.add(process2);
			return processList ;
		}
		FactoryProcessVo process3 = new FactoryProcessVo();
		process3.setProcessName("财务审核");
		process3.setProcessStatus(false);
		FactoryProcessVo process4 = new FactoryProcessVo();
		process4.setProcessName("发货（部分发货）");
		process4.setProcessStatus(false);
		FactoryProcessVo process6 = new FactoryProcessVo();
		process6.setProcessName("已收货");
		process6.setProcessStatus(false);
		if(orderStatus >= 1){
			process1.setProcessName("业务审核");
			process1.setProcessStatus(true);
		}
		if(orderStatus >=2 && !StringUtils.isEmpty(process3.getProcessName())&&
				processEntity.getFinanceReview() == 0){
			process3.setProcessName("财务审核");
			process3.setProcessStatus(true);
		}
		if(orderStatus >= 3 && !StringUtils.isEmpty(process4.getProcessName())
				&&processEntity.getShipConfirm() == 0){
			process4.setProcessName("发货（部分发货）");
			process4.setProcessStatus(true);
		}
		if(orderStatus >= 5 && !StringUtils.isEmpty(process6.getProcessName())
				&&processEntity.getReceivingConfirm() ==0){
			process6.setProcessName("已收货");
			process6.setProcessStatus(true);
		}
		FactoryProcessVo process7 = new FactoryProcessVo();
		if(orderStatus == 6){
			process7.setProcessName("完成");
			process7.setProcessStatus(true);
		}else{
			process7.setProcessName("完成");
			process7.setProcessStatus(false);
		}
		processList.add(process3);
		processList.add(process4);
		processList.add(process6);
		processList.add(process7);
		return processList;
	}
	
	@RequestMapping(value="/findForOrder")
	@ResponseBody
	public void findProductForOrderCoyp(HttpServletRequest req,HttpServletResponse resp, Long orderId){
		Long facId = getCurrentAgencyUser().getFacId();
		String tableName = Agency.getTableName(facId);
		Long ageId = getCurrentAgencyUser().getAgeId();
		List<OrderDetailEntity> detailList = detailService.selectByOrderId(orderId,null,null);
		List<String> skuIds = new ArrayList<>();
		if(detailList.isEmpty()){
			doResult(resp, false, StatusCode.NORETRUNDATA, null, "没有找到订单详情数据。");
		}
		for(OrderDetailEntity detail : detailList){
			skuIds.add(detail.getSkuId()+"");
		}
		List<OrderDetailVo> productForCopy = agency_orderService.findProductForOrderCopy(tableName, skuIds,ageId); 
		doResult(resp, true, StatusCode.FINDSUCCESS, productForCopy, ResultType.FIND_SUCCESS);
	}
}
